package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 保存关注行为方法
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询行为实体类，关注行为值能登录用户
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户行为实体数据不存在");
        }
        //判断关注行为是否存在
        ApFollowBehavior apFollowBehavior = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId()));
        if(apFollowBehavior!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已经关注过了该作者");
        }
        //封装参数插入数据
         apFollowBehavior = new ApFollowBehavior();
        apFollowBehavior.setCreatedTime(new Date());
        apFollowBehavior.setFollowId(dto.getFollowId());
        apFollowBehavior.setArticleId(dto.getArticleId());
        apFollowBehavior.setEntryId(apBehaviorEntry.getId());
        save(apFollowBehavior);
        //返回结果
        return ResponseResult.okResult();

    }
}
